import React, { useState } from "react";
import {
  Row,
  Col,
  Input,
  Select,
  Button,
  DatePicker,
  PageHeader,
  message,
  Breadcrumb,
} from "antd";

import moment from "moment";
import { Link } from "react-router-dom";

import BraftEditor from "braft-editor";
import "braft-editor/dist/index.css";
import { _updateNews } from "../../util/api/news/index";

const url = require("../../util/conUrl");

class AddArticle extends React.Component {
  state = {
    // 创建一个空的editorState作为初始值
    editorState: BraftEditor.createEditorState(null),
    blog_title: "",
    blog_time: "",
    blog_id:null
  };

  UNSAFE_componentWillMount = () => {
    let htmlContent = this.props.location.state.blog_content;
    this.setState({
      editorState: BraftEditor.createEditorState(htmlContent),
      blog_title: this.props.location.state.blog_title,
      blog_time: this.props.location.state.blog_time,
      blog_id: this.props.location.state.blog_id,
    });
  };
  submitContent = async () => {
    if (!this.state.blog_title) {
      message.error("请填写标题");
      return false;
    }
    if (!this.state.editorState) {
      message.error("请填写内容");
      return false;
    }
    if (!this.state.blog_time) {
      message.error("请选择日期");
      return false;
    }
    // this.setState({ isLoading: true });
    const htmlString = this.state.editorState.toHTML();
    let tempData = {
      blog_title: this.state.blog_title,
      blog_content: htmlString,
      blog_time: this.state.blog_time,
    };
    _updateNews(this.state.blog_id,tempData)
      .then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          this.setState({ isLoading: false });
          message.success("修改成功", 1.5).then(() => {
            window.history.back();
          });
        }
      })
      .catch(() => {
        this.setState({ isLoading: false });
        message.error("服务器错误");
      });
  };

  handleEditorChange = (editorState) => {
    this.setState({ editorState });
  };
  onInputChange = (e) => {
    let inputValue = e.target.value;
    let inputName = e.target.name;
    this.setState({
      [inputName]: inputValue,
    });
  };
  dateOnChange = (date, dateString) => {
    this.setState({
      blog_time: moment(date).valueOf(),
    });
  };
  // 预览
  preview = () => {
    if (window.previewWindow) {
      window.previewWindow.close();
    }
    window.previewWindow = window.open();
    window.previewWindow.document.write(this.buildPreviewHtml());
    window.previewWindow.document.close();
  };
  buildPreviewHtml() {
    return `
      <!Doctype html>
      <html>
        <head>
          <title>Preview Content</title>
          <style>
            html,body{
              height: 100%;
              margin: 0;
              padding: 0;
              overflow: auto;
              background-color: #f1f2f3;
            }
            .container{
              box-sizing: border-box;
              width: 1000px;
              max-width: 100%;
              min-height: 100%;
              margin: 0 auto;
              padding: 30px 20px;
              overflow: hidden;
              background-color: #fff;
              border-right: solid 1px #eee;
              border-left: solid 1px #eee;
            }
            .container img,
            .container audio,
            .container video{
              max-width: 100%;
              height: auto;
            }
            .container p{
              white-space: pre-wrap;
              min-height: 1em;
            }
            .container pre{
              padding: 15px;
              background-color: #f1f1f1;
              border-radius: 5px;
            }
            .container blockquote{
              margin: 0;
              padding: 15px;
              background-color: #f1f1f1;
              border-left: 3px solid #d1d1d1;
            }
          </style>
        </head>
        <body>
          <div class="container">${this.state.editorState.toHTML()}</div>
        </body>
      </html>
    `;
  }

  render() {
    const myUploadFn = (param) => {
      const serverURL = "/api/up_news";
      const xhr = new XMLHttpRequest();
      const fd = new FormData();

      const successFn = (res) => {
        // 假设服务端直接返回文件上传后的地址
        // 上传成功后调用param.success并传入上传后的文件地址
        param.success({
          url: `/file/news/` + JSON.parse(xhr.response).data.data.filename,
          meta: {
            id: "xxx",
            title: "教学视频",
            alt: "教学",
            loop: false, // 指定音视频是否循环播放
            autoPlay: false, // 指定音视频是否自动播放
            controls: true, // 指定音视频是否显示控制栏
            poster: url.api + "/file/qt/fm.png", // 指定视频播放器的封面
          },
        });
      };

      const progressFn = (event) => {
        // 上传进度发生变化时调用param.progress
        param.progress((event.loaded / event.total) * 100);
      };

      const errorFn = (response) => {
        // 上传发生错误时调用param.error
        param.error({
          msg: "unable to upload.",
        });
      };

      xhr.upload.addEventListener("progress", progressFn, false);
      xhr.addEventListener("load", successFn, false);
      xhr.addEventListener("error", errorFn, false);
      xhr.addEventListener("abort", errorFn, false);

      fd.append("file", param.file);
      xhr.open("POST", serverURL, true);
      xhr.send(fd);
    };
    const { editorState } = this.state;
    const excludeControls = ["emoji"];
    const extendControls = [
      {
        key: "custom-button",
        type: "component",
        component: (
          <button
            type="button"
            className="control-item button upload-button"
            data-title="预览"
            onClick={this.preview}
          >
            预览
          </button>
        ),
      },
      "fullscreen",
    ];
    return (
      <div>
        <Breadcrumb style={{ margin: "16px 0" }}>
          <Breadcrumb.Item>
            <Link to="/m/index">首页</Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>通告管理</Breadcrumb.Item>
          <Breadcrumb.Item>编辑通告</Breadcrumb.Item>
        </Breadcrumb>
        <div className="admin-body" style={{ padding: 24, minHeight: 360 }}>
          <PageHeader
            ghost={false}
            onBack={() => window.history.back()}
            subTitle="返回"
          ></PageHeader>
          <Row gutter={5}>
            <Col span={24}>
              <Row gutter={10}>
                <Col span={16}>
                  <Input
                    placeholder="通告标题"
                    size="large"
                    onChange={this.onInputChange}
                    name="blog_title"
                    value={this.state.blog_title}
                  />
                </Col>

                <Col span={4}>
                  <DatePicker
                    placeholder="发布日期"
                    size="large"
                    onChange={this.dateOnChange}
                  />
                </Col>
                <Col span={4}>
                  <Button
                    type="primary"
                    size="large"
                    block
                    onClick={this.submitContent}
                  >
                    保存修改
                  </Button>
                </Col>
              </Row>
              <br />
              <Row gutter={10}>
                <Col span={24}>
                  <div className="my-component">
                    <BraftEditor
                      value={editorState}
                      onChange={this.handleEditorChange}
                      onSave={this.submitContent}
                      extendControls={extendControls}
                      excludeControls={excludeControls}
                      media={{ uploadFn: myUploadFn }}
                    />
                  </div>
                </Col>
              </Row>
            </Col>
          </Row>
        </div>
      </div>
    );
  }
}

export default AddArticle;
